package de.slothsoft.wasbinich.core.database.webservice;

import java.lang.reflect.Type;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class StringArrayTypeAdapter implements JsonSerializer<String[]>, JsonDeserializer<String[]> {

    public static final String SEPARATOR = ","; //$NON-NLS-1$

    @Override
    public String[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
	    throws JsonParseException {
	String[] result = json.getAsString().split(SEPARATOR);
	for (int i = 0; i < result.length; i++) {
	    result[i] = result[i].trim();
	}
	return result;
    }

    @Override
    public JsonElement serialize(String[] src, Type typeOfSrc, JsonSerializationContext context) {
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < src.length; i++) {
	    if (i > 0) {
		sb.append(SEPARATOR);
	    }
	    sb.append(src[i]);
	}
	return new JsonPrimitive(sb.toString());
    }

}
